package com.dgut.app.filters;

import com.dgut.common.utils.ApiException;
import com.dgut.common.utils.ErrorEnum;
import com.dgut.common.utils.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @author IT00ZYQ
 * @Date 2021/2/5 20:57
 **/
@Component
public class TokenAuthFilter extends OncePerRequestFilter {

    /**
     * 不进行TOKEN验证的URL
     */
    private final static String ERROR_CONTROLLER = "/app/filter/error";
    private final static String LOGIN = "/app/user/login";
    private final static String REGISTER = "/app/user/register";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String url = request.getRequestURI();
        boolean pass = url.equals(ERROR_CONTROLLER) ||
                url.equals(REGISTER) || url.startsWith(LOGIN);
        // 为不需要TOKEN校验的请求, 直接放行
        if (pass) {
            chain.doFilter(request, response);
            return ;
        }
        // 设置编码
        response.setCharacterEncoding("utf-8");

        // 获取请求头中的token
        String token = request.getHeader(JwtUtil.HEADER);

        if (StringUtils.isBlank(token)) {
            request.setAttribute("exception",
                    new ApiException(ErrorEnum.NO_HAVE_TOKEN));
            request.getRequestDispatcher("/app/filter/error")
                    .forward(request, response);
            return;
        }

        // 进行TOKEN校验
        try{
            JwtUtil.getTokenClaim(token);
        } catch (ExpiredJwtException e) {
            request.setAttribute("exception",
                    new ApiException(ErrorEnum.TOKEN_EXPIRED));
            request.getRequestDispatcher("/app/filter/error")
                    .forward(request, response);
            return;
        } catch (Exception e) {
            request.setAttribute("exception",
                    new ApiException(ErrorEnum.INVALID_TOKEN));
            request.getRequestDispatcher("/app/filter/error")
                    .forward(request, response);
            return;
        }
        chain.doFilter(request, response);
    }
}
